# -*- coding: utf-8 -*-
# @Time    : 20210603
# @Author  : 柿子
# @File    : task.py

import os
import sys


def path_hint() -> str:
    """
    判断路径是否正确
    """
    while True:
        paths_list = sys.argv
        if len(paths_list) == 2:
             path = paths_list[1]
        else:
            path: str = os.path.abspath(input("请输入路径:\n").replace('\\','/'))
        path = path[:-1] if path.endswith("/") else path
        if os.path.isdir(path) or os.path.isfile(path):
            if path.startswith('.') or path.replace('/','') != "":
                break
            print('路径请不要以"/"开头')
        print("输入的地址有误")
    return path


def file_size_formating(size: int) -> tuple:
    """
    size: int 对输入的文件大小进行重新计算
    """
    counts: int = 0
    while size >= 2 ** 10 and counts < 4:
        counts += 1
        size /= 2 ** 10
    return size, "b" if counts < 1 else (
        "KB" if counts < 2 else ("MB" if counts < 3 else ("GB" if counts < 4 else "TB"))
    )


def filepath_getter(path: str) -> dict:
    """
    + path: str 输入指定目录地址
    + return :: dict {文件路径:文件大小}
    """
    output_paths: dict = {}
    # 遍历获取的文件名
    for f in os.listdir(path) if not os.path.isfile(path) else [path]:
        p: str = path + "/" + f
        n: int = 1 + len(p.split("/")) - len(path.split("/"))

        if os.path.isdir(p):
            print(".{} {}".format("--" * n, p))
            output_paths.update(filepath_getter(p))  # 递归下

        elif os.path.isfile(p):
            s = os.path.getsize(p)
            # 调用函数获取文件大小和相应单位
            filesize, units = file_size_formating(s)
            print("|{} {: >7.2f} {: >2} >> {}".format(
                  "--" * n, filesize, units, f))
            output_paths[p] = s

    return output_paths


if __name__ == "__main__":
    path: str = path_hint()
    o: dict = filepath_getter(path)
    size: int = sum(o.values())
    filesize, units = file_size_formating(sum(o.values()))
    print("""\n\n{} {} b >> 文件尺寸 {: <7.2f} {}\n路径 {}
          """.format(len(o.keys()), size, filesize, units, path))

    fkey = list(o.keys())
    fvalues = list(o.values())
    max_file_size = max(fvalues)
    filesize, units = file_size_formating(max_file_size)
    print("""\n最大文件\n{} b >> 文件尺寸 {: <7.2f} {}\n路径 {}
          """.format(max_file_size, filesize, units, fkey[fvalues.index(max_file_size)]))
    
    min_file_size = min(fvalues)
    filesize, units = file_size_formating(min_file_size)
    print("""\n最小文件\n{} b >> 文件尺寸 {: <7.2f} {}\n路径 {}
          """.format(min_file_size, filesize, units, fkey[fvalues.index(min_file_size)]))